<template>
  <a-spin size="large" :spinning="spinloading">
    <div class="content_wrapper">
      <div>
        <a-card mb-4>
          <a-form :model="queryParams" :label-col="{ style: { width: '120px' } }" ref="queryForm">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item name="systemId" label="模板名称">
                  <a-input v-model:value="queryParams.systemId"/>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item name="bussinessId" label="模板编号">
                  <a-input v-model:value="queryParams.bussinessId"/>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item name="isSuccess" label="是否成功">
                  <a-select v-model:value="queryParams.isSuccess"  >
                    <a-select-option v-for="item in options.isSuccess" placeholder="请选择"
                                     :key="item.value"
                                     :value="item.value">{{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>

              </a-col>

              <a-col :span="8">
                <a-form-item name="operatorBeginTime" label="操作开始时间">
                  <a-range-picker style="width: 100%" show-time v-model:value="queryDate.planStartTime"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  value-format="YYYY-MM-DD HH:mm:ss"></a-range-picker>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-space flex justify-end w-full>
                  <a-button :loading="loading" type="primary" @click="onSearch"> 查询</a-button>
                  <a-button :loading="loading" @click="onReset"> 重置</a-button>

                </a-space>
              </a-col>

            </a-row>

          </a-form>
        </a-card>

        <a-card>

          <a-table :loading="loading"
                   :columns="columns" :row-key="(record) => record.id"
                   :scroll="{ x: '100%' }" :data-source="dataList" :pagination="pagination">
            <template #bodyCell="scope">
              <template v-if="scope?.column?.dataIndex === 'isSuccess'">
                <div>
                  <a-tag color="success" :bordered="false" v-if="scope.record.isSuccess">
                    <template #icon>
                      <check-circle-outlined/>
                    </template>
                    执行成功
                  </a-tag>
                  <a-tag color="error" :bordered="false" v-else>
                    <template #icon>
                      <close-circle-outlined/>
                    </template>
                    执行失败
                  </a-tag>
                </div>
              </template>
              <template v-if="scope?.column?.dataIndex === 'printFileUrl'">
                <div>
                  <a-space>
                    <a class="button" @click="() => handleDownload(scope.record.printFileUrl)">
                      {{scope.record.printFileUrl}}
                    </a>
                  </a-space>
                </div>
              </template>
              <template v-if="scope?.column?.dataIndex === 'action'">
                <div>
                  <a-space>
                    <a class="button" @click="() => handleView(scope.record)">查看</a>
                  </a-space>
                </div>
              </template>


            </template>
          </a-table>
        </a-card>

      </div>
    </div>

    <a-modal centered width="50%" v-model:open="open"
             @cancel="cancelModal"
             :title="'查看'">
      <div style="padding: 16px;max-height: 50vh;overflow: auto">
        <a-form ref="formRef" :model="formModel" :rules="rules"
                :disabled="true"
                :label-col="{ style: { width: '140px' } }"
                label-align="right">

          <a-form-item name="systemId" label="模板名称">
            <div>{{ formModel.systemId }}</div>
            <!--            <a-input v-model:value="" placeholder="请输入" allow-clear/>-->
          </a-form-item>
          <a-form-item name="bussinessId" label="模板编号">
            <div>{{ formModel.bussinessId }}</div>

          </a-form-item>
          <a-form-item name="mpUrl" label="模板文件">
            <div>
              <a-typography-link @click="handleDownload(formModel.mpUrl)"> {{
                  formModel.mpUrl
                }}
              </a-typography-link>
            </div>

          </a-form-item>
          <a-form-item name="printFileUrl" label="打印文件地址">
            <div>
              <a class="button" @click="() => handleDownload(formModel.printFileUrl)">
                {{formModel.printFileUrl}}
              </a>
            </div>

          </a-form-item>
          <a-form-item name="isSuccess" label="是否成功">
            <div>
              <a-tag color="success" :bordered="false" v-if="formModel.isSuccess">
                <template #icon>
                  <check-circle-outlined/>
                </template>
                执行成功
              </a-tag>
              <a-tag color="error" :bordered="false" v-else>
                <template #icon>
                  <close-circle-outlined/>
                </template>
                执行失败
              </a-tag>
            </div>
          </a-form-item>
          <a-form-item name="printData" label="打印数据">
            <div>{{ formModel.printData }}</div>

          </a-form-item>
          <a-form-item name="errMessage" label="报错信息">
            <div>{{ formModel.errMessage }}</div>

          </a-form-item>

          <a-form-item name="operatorTime" label="操作时间">
            <div>{{ formModel.operatorTime }}</div>

          </a-form-item>


        </a-form>

      </div>
      <template #footer>
        <a-button type="primary" @click="open=false">关闭</a-button>
      </template>
    </a-modal>

  </a-spin>
</template>

<script lang="ts" setup>
import {computed, createVNode, onMounted, reactive, ref, shallowRef} from 'vue'
import {useMessage} from '@/hooks/useMessage'
import type {PaginationProps} from 'ant-design-vue'
import {message, Modal} from 'ant-design-vue'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import {UploadOutlined} from "@ant-design/icons-vue";
import moment from 'moment'

import * as api from './service'

import {
  DownOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import {useI18n} from 'vue-i18n'
import {listPrintRecord} from "./service";

const {t} = useI18n()
const {createMessage} = useMessage()
const spinloading = ref<Boolean>(false)

const columns = shallowRef([
  {
    title: '序号',
    dataIndex: 'no',
    width: 60,
    customRender: ({text, record, index}) => {
      return index + 1
    }
  },
  {title: '模板名称', dataIndex: 'systemId', ellipsis: true},
  {title: '模板编号', dataIndex: 'bussinessId', ellipsis: true},
  {title: '打印文件地址', dataIndex: 'printFileUrl', ellipsis: true},
  // {title: '打印数据', dataIndex: 'printData', ellipsis: true},
  {title: '是否成功', dataIndex: 'isSuccess', ellipsis: true},
  {title: '报错信息', dataIndex: 'errMessage', ellipsis: true},
  {title: '操作时间', dataIndex: 'operatorTime', width: 160, ellipsis: true},
  {title: '操作', dataIndex: 'action', width: 160}

])

const options = reactive({
  rules: [],
  isSuccess: [
    {
      label: '成功',
      value: 1
    },
    {
      label: '失败',
      value: 0
    },

  ]

})

const queryForm = ref()
const dataList = ref<Array>([])
const total = ref<Number>(0)
const loading = ref<Boolean>(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 0,
  showSizeChanger: true,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    getListData()
  },
  showTotal: (total) => `共${total}条`
})
const selectedRowKeys = ref([])
const rowSelections = computed(() => {
  return {
    selectedRowKeys: selectedRowKeys,
    onChange: (val) => {
      selectedRowKeys.value = val
    }
  }
})
const expand = ref(false)
//查询参数
const queryDate = ref({
  planStartTime: null,
  planEndTime: null
})
const queryParams = ref({})
//弹窗
const open = ref(false)
const viewMode = ref(false)
const formModel = ref({})
const formRef = ref()
const fileList = ref([])
// 校验规则
const rules = {
  systemId: [{required: true, message: '不能为空', trigger: 'change'}],
  bussinessId: [{required: true, message: '不能为空', trigger: 'change'}],
  version: [{required: true, message: '不能为空', trigger: 'change'}],
  fromVersion: [{required: true, message: '不能为空', trigger: 'change'}],
  // mpUrl: [{required: true, message: '不能为空', trigger: 'change'}],
  validStart: [{required: true, message: '模板生效开始时间不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {

        if (formModel.value.validStart && formModel.value.validEnd) {
          if (moment(formModel.value.validStart).isSameOrAfter(moment(formModel.value.validEnd))) {
            return Promise.reject('开始时间不能晚于结束时间');
          }
        }
        return Promise.resolve()
      }, trigger: 'change'
    }
  ],
  validEnd: [
    {required: true, message: '模板生效结束时间不能为空', trigger: 'change'},
    {
      validator: (rule, value) => {
        if (formModel.value.validStart && formModel.value.validEnd) {
          if (moment(formModel.value.validStart).isSameOrAfter(moment(formModel.value.validEnd))) {
            return Promise.reject('开始时间不能晚于结束时间');
          }
        }
        return Promise.resolve()
      }, trigger: 'change'
    }
  ],


}
const getListData: (param: Boolean) => void = async () => {
  loading.value = true

  let params = {
    ...queryParams.value,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  if (queryDate.value.planStartTime && queryDate.value.planStartTime.length) {
    console.log(queryDate.value.planStartTime)
    params.operatorBeginTime = queryDate.value.planStartTime[0]
    params.operatorEndTime = queryDate.value.planStartTime[1]
  }
  const res = await api.listPrintRecord(params)
  dataList.value = res.data
  pagination.total = res.totalCount
  loading.value = false
}

onMounted(() => {
  getOptions()
  getListData()
})

function getOptions() {

}

async function onSearch() {
  pagination.current = 1
  await getListData()
}

function clear() {
  selectedRowKeys.value = []

  getListData()
}

async function onReset() {
  // 清空所有参数重新请
  formRef.value?.resetFields()
  queryDate.value = {
    planStartTime: null,
    planEndTime: null
  }
  queryParams.value = {}
  await getListData()
}


function handleView(record) {
  viewMode.value = true
  api.getPrintRecord(record.id).then(res => {
    formModel.value = res.data
    fileList.value = [{
      name: formModel.value.mpUrl,
      url: formModel.value.mpUrl
    }]

    open.value = true


  })
}

function cancelModal() {
  open.value = false
  viewMode.value = false

  getListData()
}


async function handleDownload(mpUrl) {
  if(!mpUrl) return
  spinloading.value = true
  try {
    const link = document.createElement('a')
    link.href = mpUrl
    // link.download = (record.systemName + '.zip') || 'file.zip' // 指定文件名，可选默认值
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

  } finally {
    spinloading.value = false
  }

}

</script>

<style lang="less" scoped>
.content_wrapper {
}

.form_search {
  padding: 16px 10px;
}

.ant-uploader {
  padding: 12px;
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  align-items: center;

  /deep/ .ant_upload_class {
    width: 100%;
  }

  /deep/ .ant-upload {
    width: 100%;
  }

  .upload_area {
    width: 100%;
    height: 200px;
    border: 1px dotted #999999;
    display: flex;

    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .action-icon {
    font-size: 50px;
    color: #999;
    text-align: center;
  }

  .ant-upload-text {
    margin-top: 8px;
    color: #666666;
    text-align: center;
  }

  /deep/ .ant-upload-list-item-name {
    text-wrap: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
